package com.edmendst.xmall.service.impl;

import com.edmendst.xmall.dto.CartInfo;
import com.edmendst.xmall.mapper.CartMapper;
import com.edmendst.xmall.mapper.ProductMapper;
import com.edmendst.xmall.pojo.Cart;
import com.edmendst.xmall.pojo.CartExample;
import com.edmendst.xmall.pojo.Product;
import com.edmendst.xmall.service.CartService;
import com.edmendst.xmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductMapper productMapper;

    /*
     购物车为空--》创建购物车
     购物车不为空--》通过用户id+productID查询是否已添加该商品，有则商品+1，没有则创建
     */
    @Override
    public String addCart(CartInfo cartInfo) {
        // 参数校验
        if (cartInfo.getUserId() == null || cartInfo.getProductId() == null) {
            throw new IllegalArgumentException("用户ID和商品ID不能为空");
        }
        if (cartInfo.getQuantity() <= 0) {
            throw new IllegalArgumentException("商品数量必须大于0");
        }
        // 精确查询当前用户的同款商品
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(cartInfo.getUserId())
                .andProductIdEqualTo(cartInfo.getProductId());

        List<Cart> existing = cartMapper.selectByExample(example);

        // 存在相同商品
        if (!existing.isEmpty()) {
            Cart dbCart = existing.get(0);
            dbCart.setQuantity(dbCart.getQuantity() + cartInfo.getQuantity()); // 累加数量
            cartMapper.updateByPrimaryKeySelective(dbCart);
            return "商品数量更新成功";
        } else {
            Cart cart = new Cart(cartInfo.getCartId(), cartInfo.getUserId(), cartInfo.getProductId(), cartInfo.getQuantity(), cartInfo.getSelected());
            cartMapper.insertSelective(cart);
            return "新增商品成功";
        }
    }


    //是否选中
    @Override
    public String changeCart(CartInfo cartInfo) {
        if (cartInfo.getUserId() == null || cartInfo.getProductId() == null) {
            throw new IllegalArgumentException("用户ID和商品ID不能为空");
        }
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(cartInfo.getUserId())
                .andProductIdEqualTo(cartInfo.getProductId());
        List<Cart> carts = cartMapper.selectByExample(example);
        if (carts.size() == 1) {
            Cart cart = carts.get(0);
            if (cart.getSelected()) {
                cart.setSelected(false);
                cartMapper.updateByPrimaryKeySelective(cart);
            } else {
                cart.setSelected(true);
                cartMapper.updateByPrimaryKeySelective(cart);
            }
            return "修改成功";
        }
        return "查询到多个商品，商品不匹配";
    }

    //修改商品数量
    @Override
    public String updateCart(CartInfo cartInfo) {
        if (cartInfo.getUserId() == null || cartInfo.getProductId() == null) {
            throw new IllegalArgumentException("用户ID和商品ID不能为空");
        }
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(cartInfo.getUserId())
                .andProductIdEqualTo(cartInfo.getProductId());
        List<Cart> carts = cartMapper.selectByExample(example);
        if (carts.size() == 1) {
            Cart cart = carts.get(0);
            if (cartInfo.getOpcode() == 1) {  //操作码（1：+1，0：-1）
                cart.setQuantity(cart.getQuantity() + 1);
                cartMapper.updateByPrimaryKeySelective(cart);
                return "修改成功+1";
            } else {
                if (cart.getQuantity() <= 1) {
                    return "商品数量已经最小，无法减少";
                } else {
                    cart.setQuantity(cart.getQuantity() - 1);
                    cartMapper.updateByPrimaryKeySelective(cart);
                    return "修改成功-1";
                }
            }
        }
        return "查询到多个商品，商品不匹配";
    }

    @Override
    public String deleteCart(CartInfo cartInfo) {
        if (cartInfo.getUserId() == null || cartInfo.getProductId() == null) {
            throw new IllegalArgumentException("用户ID和商品ID不能为空");
        }
        CartExample example = new CartExample();
        example.createCriteria()
                .andUserIdEqualTo(cartInfo.getUserId())
                .andProductIdEqualTo(cartInfo.getProductId());
        if (cartMapper.deleteByExample(example) == 1) {
            return "删除成功";
        }
        return "删除失败";
    }

    @Override
    public List<CartInfo> getCart(String userName) {
        Integer userIdByUserName = userService.selectUserIdByUserName(userName);
        if (userIdByUserName != null) {
            CartExample example = new CartExample();
            example.createCriteria()
                    .andUserIdEqualTo(userIdByUserName);
            List<Cart> carts = cartMapper.selectByExample(example);
            List<CartInfo> cartInfos = new ArrayList<>();

            for (int i = 0; i < carts.size(); i++) {
                CartInfo cartInfo = new CartInfo();


                Product product = productMapper.selectByPrimaryKey(carts.get(i).getProductId());
                cartInfo.setCartId(carts.get(i).getCartId());
                cartInfo.setUserId(carts.get(i).getUserId());
                cartInfo.setProductId(carts.get(i).getProductId());
                cartInfo.setQuantity(carts.get(i).getQuantity());
                cartInfo.setSelected(carts.get(i).getSelected());
                cartInfo.setProductName(product.getProductName());
                cartInfo.setProductPrice(product.getProductPrice());
                cartInfo.setProductStock(product.getProductStock());
                cartInfo.setProductImage(product.getProductCoverImage());
                cartInfos.add(cartInfo);

            }
            return cartInfos;
        }
        return Collections.emptyList(); // 用户不存在时返回空列表
    }

}
